<?php

class Store_Form_Product extends YouNet_Form
{
	protected $_element_decorators = array(
		'ViewHelper',
		'Description',
		'Errors',
		array('HtmlTag', array('tag' => 'dd')),
		array('Label', array('tag' => 'dt')),
	);
	protected $_file_decorators = array(
		'File',
		'Description',
		'Errors',
		array('HtmlTag', array('tag' => 'dd')),
		array('Label', array('tag' => 'dt')),
	);

	/**
	 *
	 * @var Core_Model_Product
	 */
	protected $_productRow	= null;
	/**
	 *
	 * @var Core_Model_Store
	 */
	protected $_storeRow	= null;

	protected $_arrImageElements		= array();
	protected $_arrImageDescriptions	= array();
	
	protected $_cancelUrl				= '';
    protected $_shopping_cart_setting   = false;
    
    public function __construct(array $options = null)
	{
        if (!empty($options))
		{
			if ( isset($options['product']) && ($options['product'] instanceof Core_Model_Product) )
			{
				$this->_productRow	= $options['product'];
			}
			if( isset($options['store']) && ($options['store'] instanceof Core_Model_Store) )
			{
				$this->_storeRow	= $options['store'];
			}
            if(isset($options['store']) && $options['store']['shopping_cart_setting'] == Core_Model_DbTable_Stores::STATUS_SHOPPING_CART_SETTING)
            {
                $this->_shopping_cart_setting = true;
            }
		}
		parent::__construct();
	}

	public function init()
	{
		parent::init();
		$this->setAttrib('class', 'sm_form classic');
		$this->setName('product-form');

		$this->_initName();
		$this->_initSKU();
		$this->_initDescription();
		$this->_initSystemCategory();
		$this->_initCustomCategory();
		$this->_initProductImages();

		$this->addElement('text', 'price', array(
			'label' => 'PRODUCT_PRICE'
		));
		$this->getElement('price')->getDecorator('Label')->setOption('escape', false);
		$this->getElement('price')->getDecorator('Description')->setOption('class', 'price_description');
		$this->getElement('price')->setDescription($this->_storeRow->getUnitCode() . '</p><p class="hint">' . sprintf($this->getTranslator()->translate('PRODUCT_PRICE_HINT'), '"."'));
		$this->getElement('price')->getDecorator('Description')->setOption('escape', false);		
		$this->getElement('price')->addFilter('PregReplace', array(
             'match' => '/[ ]/', 
             'replace' => ''
		));
		$this->price->addValidator('float', true, array('locale' => $this->_storeRow->getLocale()));
        $this->price->addValidator(new Zend_Validate_GreaterThan(0));
        
        /* phuttt 16/10/2012 : add old price */
        $this->addElement('text', 'old_price', array(
			'label' => 'PRODUCT_PRICE_OLD'
		));
		$this->getElement('old_price')->getDecorator('Label')->setOption('escape', false);
		$this->getElement('old_price')->getDecorator('Description')->setOption('class', 'price_description');
		$this->getElement('old_price')->setDescription($this->_storeRow->getUnitCode() . '</p><p class="hint">' . sprintf($this->getTranslator()->translate('PRODUCT_PRICE_OLD_HINT'), '"."'));
		$this->getElement('old_price')->getDecorator('Description')->setOption('escape', false);		
		$this->getElement('old_price')->addFilter('PregReplace', array(
             'match' => '/[ ]/', 
             'replace' => ''
		));
		$this->old_price->addValidator('float', true, array('locale' => $this->_storeRow->getLocale()));
        $this->old_price->addValidator(new Zend_Validate_GreaterThan(0));
        /* phuttt 16/10/2012 : add old price END*/
        
        if($this->_shopping_cart_setting == false)
        {
            $this->_initLink();
        }
		$this->_initStatus();
		$this->_initButtons();
	}
	
	public function setCancelUrl($url)
	{
		$this->_cancelUrl = $url;
	}
	
	public function getCancelUrl()
	{
		return $this->_cancelUrl;
	}
	
	private function _initSKU()
	{
		$this->addElement('text', 'sku', array(
			'label' => 'PRODUCT_SKU',
			'filters' => array('StringTrim')
		));
		$maxLengthValidator = new Zend_Validate_StringLength(array('max' => 255));
		$this->sku->addValidator($maxLengthValidator);
	}
	private function _initButtons()
	{
		$this->addElement('submit', 'submit', array(
			'label' => 'BUTTON_SAVE',
			'onclick' => 'window.isSubmitting = true;',
			'class' => 'greenbutton spacing'
		));
		$this->addElement('submit', 'cancel', array(
			'label' => 'BUTTON_CANCEL',
			'onclick' => 'window.isSubmitting = false;',
			'class' => 'graybutton'
		));
		$this->submit->removeDecorator('Label');
		$this->cancel->removeDecorator('Label');
		$this->submit->removeDecorator('HtmlTag');
		$this->cancel->removeDecorator('HtmlTag');
		
		$this->addDisplayGroup(array('submit','cancel'), 'group-btn');
	}

	private function _initName()
	{
		$this->addElement('text', 'name', array(
			'label' => 'PRODUCT_NAME',
			'required' => true,
			'filters' => array('StringTrim')
		));
		$maxLengthValidator = new Zend_Validate_StringLength(array('max' => 255));
		$maxLengthValidator->setMessage('ERROR_PRODUCT_NAME_IS_TOO_LONG', Zend_Validate_StringLength::TOO_LONG);
		$this->name->addValidator($maxLengthValidator);
	}

	private function _initDescription()
	{
		$this->addElement('RichEditor', 'description', array(
			'label' => 'PRODUCT_DESCRIPTION',
			'rows' => '3',
		));
	}

	private function _initLink()
	{
		$this->addElement('text', 'link', array(
			'label'		=> 'PRODUCT_PURCHASE',
			'filters'	=> array('StringTrim'),
			'value'		=> $this->_storeRow->purchase_info
		));
		$this->link->getDecorator('Label')->setOption('escape',false);
		$this->link->getDecorator('Description')->setOption('escape', false);
		$this->link->setDescription('STORE_PURCHASE_DEFAULT_DESCRIPTION');
		//FBSTORE-175 Add Default Value to Create Product Form
		//$this->link->addValidator(new Core_Validate_Uri());
		$maxLengthValidator = new Zend_Validate_StringLength(array('max' => 255));
		$maxLengthValidator->setMessage('ERROR_BANNER_LINK_IS_TOO_LONG', Zend_Validate_StringLength::TOO_LONG);
		$this->link->addValidator($maxLengthValidator);
	}

	private function _initSystemCategory()
	{
		if( isset($_POST['id_system_category']) )
		{
			$id_parent	= NULL;
			$is_first	= true;
			foreach($_POST['id_system_category'] as $key => $value)
			{
				$this->_addSystemCategoryWidget($key, $id_parent, $is_first == true, $value);
				$id_parent	= $value;
				$is_first	= false;
			}
			$this->addDisplayGroup(
				array_keys($_POST['id_system_category']),
				'id_system_category'
			);
		}
		else
		{
			if( !$this->_productRow )
			{
				if( $this->_storeRow->getSystemCategory() )
				{
					$id_parent			= NULL;
					$is_first			= true;
					$arrIdCategories	= $this->_storeRow
											->getSystemCategory()
											->getHierarchyIdCategories();
					$arrGroupElements	= array();
					foreach($arrIdCategories as $id)
					{
						$key = 'system_category_'.$id;
						$this->_addSystemCategoryWidget($key, $id_parent, $is_first == true, $id);
						$is_first	= false;
						$id_parent	= $id;
						$arrGroupElements[] = $key;
					}
					$this->addDisplayGroup(
						$arrGroupElements,
						'id_system_category'
					);
				}
				else
				{
					$key = 'system_category_1';
					$this->_addSystemCategoryWidget($key, NULL, true, '');

					$this->addDisplayGroup(
						array($key),
						'id_system_category'
					);
				}
			}
			else
			{
				$id_parent			= NULL;
				$is_first			= true;
				$arrIdCategories	= $this->_productRow
										->getSystemCategory()
										->getHierarchyIdCategories();
				$arrGroupElements	= array();
				foreach($arrIdCategories as $id)
				{
					$key = 'system_category_'.$id;
					$this->_addSystemCategoryWidget($key, $id_parent, $is_first == true, $id);
					$is_first	= false;
					$id_parent	= $id;
					$arrGroupElements[] = $key;
				}
				$this->addDisplayGroup(
					$arrGroupElements,
					'id_system_category'
				);
			}
		}
		$this->id_system_category->getDecorator('DtDdWrapper')->setOption(
			'dtLabel',
			'<label class="required">'.$this->getTranslator()->translate('SYSTEM_CATEGORY').'</label>'
		);
	}

	private function _addSystemCategoryWidget($key, $id_parent, $required, $value)
	{
		$arrAttributes = array(
			'label'		=> NULL,
			'required'	=> true,
			'class'		=> 'system_category',
			'belongsTo' => 'id_system_category'
		);
		$options = array('' => YouNet_Util::translate('SELECT'))+Core_Model_DbTable_Category_Systems::getArrCategories($id_parent);
		$this->addElement('select', $key, array_merge(
			$arrAttributes,
			array(
				'multiOptions'	=> $options,
				'required'		=> $required,
				'value'			=> $value
			)
		));
		$this->$key->removeDecorator('Label');
	}

	private function _initCustomCategory()
	{
		if( isset($_POST['id_custom_category']) )
		{
			$id_parent	= NULL;
			$is_first	= true;
			foreach($_POST['id_custom_category'] as $key => $value)
			{
				$this->_addCustomCategoryWidget($key, $id_parent, $is_first == true, $value);
				$is_first	= false;
				$id_parent	= $value;
			}
			$this->addDisplayGroup(
				array_keys($_POST['id_custom_category']),
				'id_custom_category'
			);
		}
		else
		{
			if( !$this->_productRow )
			{
				$key = 'custom_category_1';
				$this->_addCustomCategoryWidget($key, NULL, true, '');
				$this->addDisplayGroup(
					array($key),
					'id_custom_category'
				);
			}
			else
			{
				$id_parent			= NULL;
				$is_first			= true;
				$arrGroupElements	= array();
				$id					= 0;
				if( $this->_productRow->getCustomCategory() )
				{
					$arrIdCategories	= $this->_productRow
											->getCustomCategory()
											->getHierarchyIdCategories();
					foreach($arrIdCategories as $id)
					{
						$key = 'custom_category_'.$id;
						$this->_addCustomCategoryWidget($key, $id_parent, $is_first == true, $id);
						$is_first	= false;
						$id_parent	= $id;
						$arrGroupElements[] = $key;
					}
				}
				//Add last item
				$id		= time();
				$key	= 'custom_category_'.$id;
				$this->_addCustomCategoryWidget($key, $id_parent, $is_first == true, '');
				$arrGroupElements[] = $key;
				
				$this->addDisplayGroup(
					$arrGroupElements,
					'id_custom_category'
				);
			}
		}
		$this->id_custom_category->getDecorator('DtDdWrapper')->setOption(
			'dtLabel',
			'<label class="required">'.$this->getTranslator()->translate('CUSTOM_CATEGORY').'</label>'
		);
	}

	private function _addCustomCategoryWidget($key, $id_parent, $required, $value)
	{
		$parent_name = $id_parent?Core_Model_DbTable_Category_Customs::getInstance()->findOne($id_parent)->name:'none';
		$arrAttributes = array(
			'label'				=> NULL,
			'class'				=> 'custom_category',
			'belongsTo'			=> 'id_custom_category',
			'data-id-parent'	=> $id_parent,
			'data-parent-name'	=> $parent_name,
			'required'			=> true
		);
		$options = array('' => YouNet_Util::translate('SELECT'))+$this->_storeRow->getArrCategories($id_parent);		
		$this->addElement('select', $key, array_merge(
			$arrAttributes,
			array(
				'multiOptions'	=> $options,
				'required'		=> $required,
				'value'			=> $value
			)
		));
		$this->$key->removeDecorator('Label');
	}

	private function _initProductImages()
	{
		$arrGroupElements	= array();
		$arrImageIds		= array();
		if( count($_FILES) )
		{
			foreach($_FILES as $key => $value)
			{
				$image_key			= $key;
				$description_key	= key($_POST[$image_key]);
				$this->_addImageWidget($image_key, $description_key, $arrGroupElements);
				if( isset($_POST['productImageIds']) )
				{
					$arrImageIds		= json_decode(base64_decode($_POST['productImageIds']));
					/**
					 *@todo Need to check  $arrImageIds = $product->getArrImageId()
					 */
					if( $arrImageIds )
					{
						$arrTemp	= explode('_', $image_key);
						$id_image	= $arrTemp[1];
						if( in_array($id_image, $arrImageIds) )
						{
							$this->$image_key->setRequired(false);
						}
					}
				}
			}
		}
		else
		{
			if( !$this->_productRow )
			{
				$this->_addImageWidget('images_1', 'description_1', $arrGroupElements);
			}
			else
			{
				$listProductImages = $this->_productRow->getListProductImages();
				if( $listProductImages->count() )
				{
					$arrImageIds = array();
					foreach($listProductImages as $image)
					{
						$arrImageIds[] = $image->id;
						/*@var $image Core_Model_Product_Image*/
						$image_key			= 'images_'.$image->id;
						$description_key	= 'description_'.$image->id;
						$this->_addImageWidget($image_key, $description_key, $arrGroupElements);
						$this->$image_key->setRequired(false);
						$this->$description_key->setValue($image->description);
					}					
				}

			}
		}
		$this->addDisplayGroup($arrGroupElements,'images');
		$this->images->removeDecorator('Fieldset');
		$this->images->getDecorator('DtDdWrapper')->setOption(
			'dtLabel',
			'<label class="required">'.$this->getTranslator()->translate('PRODUCT_IMAGES').'</label>'
		);
		if( count($arrImageIds) )
		{
			$this->addElement('hidden','productImageIds',array(
				'value'	=> base64_encode(json_encode($arrImageIds)),
				'decorators' => $this->_hidden_decorators
			));
		}
	}

	private function _addImageWidget($image_key, $description_key, &$arrGroupElements)
	{
		static $is_first = true;
		$this->addElement(new YouNet_Form_Element_File($image_key, array(
			'decorators'	=> $this->_file_decorators,
			'destination'	=> UPLOAD_PATH . '/' . STORE_IMAGE_FOLDER,
			'belongsTo'		=> $image_key,
			'required'		=> true
		)));
		// ensure only 1 file
		$this->$image_key->addValidator('Count', false, 1);
		// limit to 100K
		$this->$image_key->addValidator('Size', false, 204800*5);
		// only JPEG, PNG, and GIFs
		$this->$image_key->addValidator('Extension', false, 'jpg,png,gif,jpeg');
		$this->$image_key->getValidator('Upload')->setMessage(
			$this->getTranslator()->_('ERROR_PRODUCT_IMAGE_IS_NO_FILE'), Zend_Validate_File_Upload::NO_FILE
		);
		$this->$image_key->getDecorator('Description')->setOption('placement','PREPEND');
		$this->$image_key->removeDecorator('Label');
		$this->$image_key->getDecorator('HtmlTag')->setOptions(array('tag'=>'div','class' => 'helper-image'));
		$this->_arrImageElements[] = $this->$image_key;

		$this->addElement('textarea', $description_key , array(
			'label'			=> 'PRODUCT_IMAGE_DESCRIPTION',
			'rows'			=> '3',
			'belongsTo'		=> $image_key,
		));
		$this->$description_key->removeDecorator('Label');
		$this->$description_key->removeDecorator('HtmlTag');
		$this->$description_key->getDecorator('Description')->setOption('class','hr');
		$this->$description_key->setDescription('&nbsp;');
		
		if( $is_first )
		{
			$this->$description_key->getDecorator('Description')->setOption('class','hr first');
			$this->$description_key->setDescription(sprintf(
				$this->getTranslator()->translate('IMAGE_UPLOAD_FANPAGE_HINT'), '1 MB', FANPAGE_MAX_WIDTH . 'px'
			));
			$is_first = false;
			
			$this->$description_key->getDecorator('Errors')->setOption('placement', 'APPEND');
			$this->$image_key->removeDecorator('Errors');
		}
		//$this->$image_key->removeDecorator('HtmlTag');
		
		$arrGroupElements[]				= $image_key;
		$arrGroupElements[]				= $description_key;
		$this->_arrImageDescriptions[]	= $this->$description_key;
	}
	
	public function _initStatus()
	{
		$this->addElement('checkbox', 'status', array(
			'label'				=> '',
			'checkedValue'		=> Core_Model_DbTable_Products::STATUS_SHOWN,
			'uncheckedValue'	=> Core_Model_DbTable_Products::STATUS_HIDDEN
		));
		$this->status->setValue(1);
		$this->status->setDescription('PUBLIC_ON_FANPAGE');
		$this->status->getDecorator('Description')->setOptions(array('tag' => ''));
	}
			

	public function fill(Core_Model_Product $productRow)
	{
		$values = $productRow->toArray();
		unset($values['id_custom_category']);
		unset($values['id_system_category']);
		$this->populate($values);
	}

	/**
	 *
	 * @return array
	 */
	public function getProductImageNames()
	{
		return $this->_getImageNameAndReceive();
	}

	/**
	 *
	 * @return array
	 */
	private function _getImageNameAndReceive()
	{
		$arrNames = array();
		foreach($this->_arrImageElements as $imageElement)
		{
			/* @var $imageElement Zend_Form_Element_File */
			if (!empty($imageElement))
			{
				$arrNames[$imageElement->getName()] = '';
				$image_name = $imageElement->getFileName(null, false);
				if (!empty($image_name))
				{
					/*max length: MAX_FILENAME_LENGTH + 10 + [1,4]*/
					$max_file_name_length = MAX_FILENAME_LENGTH - 16;

					if (strlen($image_name) > $max_file_name_length)
					{
						$image_name = substr($image_name, -$max_file_name_length);
					}
					$ret_name	= time() . '_' . mt_rand(0, 9999) . '_' . preg_replace('/[^A-Za-z0-9-_.]/', '', $image_name);

					$arrNames[$imageElement->getName()]	= $ret_name;

					$target		= UPLOAD_PATH . '/' . PRODUCT_IMAGE_FOLDER . '/';
					$thumbnail	= UPLOAD_PATH . '/' . PRODUCT_IMAGE_FOLDER . '/' . THUMBNAIL_IMAGE_FOLDER . '/';

					$target		.= $ret_name;
					$thumbnail	.= $ret_name;

					$imageElement->addFilter('Rename', array(
						'target' => $target
					));

					if ($imageElement->receive())
					{
						$this->_cropImage($target, $thumbnail);
					}
				}
			}
		}
		return $arrNames;
	}

	protected function _cropImage($source,$target)
	{
		Core_Util::createScaledThumbnail($source, $target, DEFAULT_PRODUCT_THUMNAIL);
	}

	private function _updatePreviousImages()
	{
		$listProductImages = $this->_productRow->getListProductImages();
		foreach( $this->_arrImageElements as $imageElement)
		{
			$arrTemp		= explode('_',$imageElement->getName());
			$id_image		= $arrTemp[1];
			$is_found		= false;
			$description	= $imageElement->getDescription();
			foreach($listProductImages as $productImage)
			{
				if( $productImage->id == $id_image)
				{
					$description .= '<span>';
					$description .= '<img src="' . $productImage->getImageThumbUrl() . '"/>';
					$description .= '</span>';

					$is_found	= true;
					break;
				}
			}
			if( !$is_found )
			{
				$description .= '<span>';
				$description .= '<img src="' . STATIC_URL . '/img/icon_noimage.png"/>';
				$description .= '</span>';
				$imageElement->getDecorator('Description')->setOption('class', 'hint no_image');
			}
			$imageElement->setDescription($description);
			$imageElement->getDecorator('Description')->setOption('escape', false);
		}
	}

	public function render(Zend_View_Interface $view = null)
	{
		if (!empty($this->_productRow))
		{
			$this->_updatePreviousImages();
		}
		else
		{
			foreach($this->_arrImageElements as $imageElement)
			{
				$description	= $imageElement->getDescription();
				$description .= '<span>';
				$description .= '<img src="' . STATIC_URL . '/img/icon_noimage.png"/>';
				$description .= '</span>';
				$imageElement->setDescription($description);
				$imageElement->getDecorator('Description')->setOption('escape', false);
				$imageElement->getDecorator('Description')->setOption('class', 'hint no_image');
			}
		}
		return parent::render($view);
	}
	
	/**
	 *
	 * @param array $data
	 * @return boolean 
	 */
	public function isValid($data)
	{
		parent::isValid($data);
		//FBSTORE-459
		//	[Product form] Input sku is duplicate,
		//	but it not display an error message and sku not be updated.
		$validSku = $this->getValue('sku');
		if( !empty($data['sku']) )
		{
			//Check only if the sku is changed
			if( empty($this->_productRow) || $this->_productRow->sku != $validSku )
			{
				if($this->_storeRow->hasSkuExist($validSku) )
				{
					$this->sku->addError($this->getTranslator()->_('ERROR_SKU_IS_EXIST'));
					$this->markAsError();
				}
			}
		}

		$imageErrorsMessages = $this->_arrImageElements[0]->getMessages();
		$this->_arrImageElements[0]->clearErrorMessages();
		$this->_arrImageDescriptions[0]->setErrors($imageErrorsMessages);
		
		return !$this->isErrors();
	}
}
